package com.atguigu.stack;

import java.util.Scanner;

public class LinkedStackDemo {
    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack();
        boolean loop=true;
        Scanner scanner = new Scanner(System.in);
        while(loop){
            System.out.println("show:展示栈");
            System.out.println("push:入栈");
            System.out.println("pop:出栈");
            System.out.println("exit:结束程序");
            System.out.println("请输入操作:");
            String next = scanner.next();
            switch (next){
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入入栈的值");
                    int i = scanner.nextInt();
                    stack.push(i);
                    break;
                case "pop":
                    try{
                        int pop = stack.pop();
                        System.out.printf("出栈值为%d\n",pop);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case "exit":
                    loop=false;
                    break;
            }
        }
        scanner.close();
        System.out.println("程序结束");
    }

}

class LinkedStackNode{
    private LinkedStackNode next;
    private int data;

    public LinkedStackNode(LinkedStackNode next, int data) {
        this.next = next;
        this.data = data;
    }

    public LinkedStackNode getNext() {
        return next;
    }

    public int getData() {
        return data;
    }
}

class LinkedStack{
    private LinkedStackNode top;

    public boolean isEmpty(){
        return top==null;
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈空...");
            return;
        }
        LinkedStackNode cache=top;
        while(cache!=null){
            System.out.printf("stack show:%d\n",cache.getData());
            cache=cache.getNext();
        }
    }

    public void push(int val){
        this.top= new LinkedStackNode(top, val);
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈空...");
        }
        int data = top.getData();
        this.top=this.top.getNext();
        return data;
    }
}
